import axios from '@/api/axios.config.js'

// 截取上传文件后缀
function getSuffix(filename) {
    let pos = filename.lastIndexOf(".");
    let suffix = "";
    if (pos != -1) suffix = filename.substring(pos);
    return suffix;
}

// 生成随机数
function randomString(len) {
    len = len || 32;
    const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
    const maxPos = chars.length;
    let pwd = "";
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

//上传文件
async function handleUploadImg(host, file) {
    //测试API地址，发布前需要更换
    let res = await axios
        .post(host)
        .catch((err) => {
            console.log(err);
        });

    let picName =
        randomString(10) + getSuffix(file.file.name);
    let keyValue = res.dir + picName;
    //注意formData里append添加的键的大小写
    let formData = new FormData();
    formData.append("name", file.file.name); // 文件名称
    formData.append("key", keyValue); // 存储在oss的文件路径
    formData.append("OSSAccessKeyId", res.accessid); // //accessKeyId
    formData.append("policy", res.policy); // policy
    formData.append("callback", res.callback); //回调地址
    formData.append("Signature", res.signature); //签名
    formData.append("success_action_status", 200);
    formData.append("file", file.file, file.file.name); // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可
    return axios
        .post(res.host, formData, {
            headers: {
                "Content-Type": "multipart/form-data",
            }
        })
        .catch((err) => {
            console.log(err);
        });
}

export default handleUploadImg;